package com.winit.common.schedule;

import com.alibaba.fastjson.JSONObject;
import com.winit.common.util.HttpClientUtil;
import com.winit.common.util.NetworkUtil;
import com.winit.ogg.manager.OggManager;
import com.winit.ogg.manager.PTServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * Created by wangjian on 17/1/4.
 */
@Component
public class Scheduler {

    private static Logger logger = LoggerFactory.getLogger(Scheduler.class);

    private static long send_time = 0l;

    static final String line_separator = "    ";

    @Autowired
    private OggManager oggManager;

    @Autowired
    private PTServiceImpl operateService;

    @Value("${send_mail_flag}")
    private boolean send_mail_flag;
    @Value("${send_mail_interval}")
    private Integer send_mail_interval;
    @Value("${send_mail_url}")
    private String send_mail_url;
    @Value("${send_mail_addr}")
    private String send_mail_addr;

    @Scheduled(cron = "0 */1 * * * ?")
    public void checkOggStatus() {
        logger.info("com.winit.common.schedule.BeetleScheduler.checkOggStatus");
        try {
            boolean flag = oggManager.getStatus().isOgg_status();
            Map map = operateService.status();
            boolean status = "RUNNING".equals((String) map.get("message"));
            if ((Integer) map.get("code") != 0 || flag != status) {
                logger.error("com.winit.common.schedule.BeetleScheduler.checkOggStatus ogg状态错误.操作状态为" + flag + ",运行状态为:" + status);
                if (send_mail_flag) {
                    long now = new Date().getTime();
                    String addr = NetworkUtil.getLocalIp();

                    StringBuffer body = new StringBuffer();
                    body.append("UCLOUD: ").append(addr).append(" OGG服务异常.").append(line_separator)
                            .append("开关状态为: ").append(flag).append(" .").append(line_separator)
                            .append("OGG服务状态为: ").append(map.get("message")).append(" .");

                    if (send_time == 0l || now - send_time >= 1000 * 60 * send_mail_interval) {
                        send_time = now;
                        sendMail(body.toString());
                    }
                }
            }
        } catch (Exception e) {
            logger.error("com.winit.common.schedule.BeetleScheduler.checkOggStatus", e);
        }
    }

    //发送告警邮件
    private void sendMail(String body) {
        JSONObject json = new JSONObject();
        json.put("bc", "");
        json.put("body", body);
        json.put("cc", "");
        json.put("subject", "OGG服务异常告警");
        json.put("to", send_mail_addr);

        logger.info("com.winit.common.schedule.Scheduler.sendMail json:" + json.toString());

        try {
            HttpClientUtil.doPostForJson(send_mail_url, json.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 检查ogg服务启动后,数据同步是否完成
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void checkOggIsComplete() {
        logger.info("com.winit.common.schedule.BeetleScheduler.checkOggIsComplete");
        try {
            oggManager.afterOggComplete();
        } catch (Exception e) {
            logger.error("com.winit.common.schedule.BeetleScheduler.checkOggStatus", e);
        }
    }

}
